<?php

class RM_Admin_OptionController extends RM_Controller {

    /**
     * provide the list JSON
     */
    public function listJsonAction(){

        $dao = new RM_Units();
        $criteria = new RM_Unit_Search_Criteria(array(), true);
        $criteria->offset = $this->_getParam('start');
        $criteria->order = $this->_getParam('sort', 'id') . ' ' . $this->_getParam('dir', 'DESC');
        $criteria->count = $this->_getParam('limit');
        $criteria->showOptionUnits = true;
        $total = $dao->getAll($criteria)->count();
        $data = $dao->getAll($criteria)->toArray();

        // get the saved associations
        $optionModel = new RM_Option();
        $selected = array();
        foreach($data as $index=>$unit){
            $units = $optionModel->getAssociated($unit['id'])->toArray();
            foreach($units as $unit){
                $selected[] = $unit['units'];
            }

            if (!empty($selected)){
                $data[$index]['units'] = implode(",", $selected);
                $selected = array(); // clear the array now
            }
        }
        
        
        $json = new stdClass;
        $json->total = $total;
        $json->data = $data;

        return array(
            'data' => $json
        );
    }

    /**
     * Provides the unit list JSON for unit selection
     */
    public function unitlistJsonAction(){

        $dao = new RM_Units;
        $units = $dao->getAll(new RM_Unit_Search_Criteria())->toArray();

        $units[] = array(
            'id' => '0',
            'name' => RM_Environment::getInstance()->getTranslation()->_('Admin.Extras.Edit','AllUnits')
        );
        return array(
            'data' => $units
        );

    }

    /**
     * Saves the Unit Option association
     */
    public function updateJsonAction(){
        $dataJson = $this->_getParam('data', '[]');

        $data = Zend_Json::decode($dataJson);
        $model = new RM_Option();
        foreach($data as $row){

            $unit_id = $row["id"];

            // remove old entries
            $model->delete("unit_id='".$unit_id."'");

            // insert the new entries
            $units = explode(",", $row["units"]);
            unset($row["units"]);
            foreach($units as $unit){
                $unitRow = array("unit_id"=>$unit_id,"units"=>$unit);
                $model->insert($unitRow);
            }
        }
    }
}